package tech.bmatch.meituan.service.impl;

import tech.bmatch.meituan.Util.DistanceUtil;
import tech.bmatch.meituan.model.Dish;
import tech.bmatch.meituan.model.Merchant;
import tech.bmatch.meituan.model.SearchParam;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class MerchantServiceImpl extends MerchantFileStoreImpl {
    private static Map<String, Merchant> merchantMap;

    /**
     * 添加商家信息
     *
     * @param merchant
     */
    public void add(Merchant merchant) {
        if (merchantMap == null) {
            merchantMap = new HashMap<String, Merchant>();
        }
        if (merchant == null) return;
        if (!merchantMap.containsValue(merchant)) {
            merchantMap.put(merchant.getId(), merchant);
        }
        List<Merchant> merchantList = merchantMap.values().stream().collect(Collectors.toList());
        store(merchantList);
    }

    /**
     * 在商家中添加菜品
     *
     * @param merchant
     * @param dishList
     */
    public void addDish(String merchant, List<Dish> dishList) {
        boolean exist = false;
        if (dishList == null) {
            return;
        }
        for (Map.Entry<String, Merchant> merchantEntry : merchantMap.entrySet()) {
            if (merchantEntry.getValue().getName().equals(merchant)) {
                merchantEntry.getValue().setDishes(dishList);
                exist = true;
            }
        }
        if (!exist) System.out.println("录入商家信息不存在");
        List<Merchant> merchantList = merchantMap.values().stream().collect(Collectors.toList());
        store(merchantList);
    }

    /**
     * 根据关键词搜索商家信息
     *
     * @param searchParam
     * @return
     */
    public List<Merchant> search(SearchParam searchParam) {
        List<Merchant> merchantList = new ArrayList<>();
        for (Map.Entry<String, Merchant> merchantEntry : merchantMap.entrySet()) {
            Merchant merchant = merchantEntry.getValue();
            double distance = DistanceUtil.getDistance(searchParam.getLon(), searchParam.getLat(), merchant.getLon(), merchant.getLat());
            merchant.setDistance(distance);
            merchantList.add(merchant);
        }
        Stream<Merchant> stream = merchantList.stream();
        if (searchParam != null && !searchParam.getName().equals("")) {
            stream = stream.filter(m -> m.getName().indexOf(searchParam.getName()) >= 0);
        }
        stream = stream.sorted((m1, m2) -> ((Double) m1.getDistance()).intValue() - ((Double) m2.getDistance()).intValue());
        return stream.collect(Collectors.toList());
    }
}
